<!--
 * @Author: 孙文豪
 * @Description: 商品库存信息
 * @Date: 2024-03-20 15:04:35
 * @LastEditTime: 2024-06-24 10:15:38
 * @LastEditors: 孙文豪
-->
<template>
  <div class="commodity-page">
    <!-- 分类输入框 -->
    <div class="add-favorites-zzc" v-if="idAddClass">
      <div class="add-favorites">
        <div class="add-item">
          <el-input
            v-model.trim="editClassName"
            maxlength="8"
            placeholder="请输入文件夹名称"
            @keydown.enter="confirmAddClassFn"
          ></el-input>
          <div class="btn-box">
            <el-button
              type="primary"
              class="add-category"
              @click="confirmAddClassFn"
              >确认</el-button
            >
            <el-button class="add-category" @click="idAddClass = false"
              >取消</el-button
            >
          </div>
        </div>
      </div>
    </div>

    <div class="classification-left">
      <!-- 点击分类按钮 -->
      <el-button type="primary" class="add-category" @click="idAddClass = true"
        >新增分类</el-button
      >
      <!-- 文件夹列表 -->
      <div class="favorites-list" v-if="commodityData.length">
        <transition-group>
          <div
            class="favorites-item"
            :class="{ active: activeClass.id === oneClass.id }"
            v-for="(oneClass, index) in commodityData"
            :key="oneClass.id"
            draggable="true"
            @dragstart="dragstart(index)"
            @dragenter="dragenter($event, index)"
            @dragover="dragover($event, index)"
            @dragend="dragend"
            @click="clickClass(oneClass)"
            @dblclick="editClassNameFn(oneClass)"
          >
            <span class="favorites-item-icon iconfont icon-JXC-liebiao2"></span>
            <span
              class="favorites-item-name"
              v-if="editClass.id !== oneClass.id"
              >{{ oneClass.className }}</span
            >
            <!-- 编辑框 -->
            <input
              v-else
              class="edit-input"
              type="text"
              placeholder="请输入文件夹名称 回车确认"
              v-model="editClassName"
              @click.stop
              @keydown.enter="confirmEditClassNameFn"
            />
            <!-- 文件夹内的产品数量 -->
            <span
              class="oneClass-in-num"
              v-if="
                oneClass.commodityLists.length ||
                oneClass.className === '默认分类'
              "
              v-MoveTips="{
                vText:
                  oneClass.className !== '默认分类'
                    ? '清空分类产品后可删除'
                    : '默认分类不可删除', // 显示的浮窗内容
                vTime: 300
              }"
              >{{ oneClass.commodityLists.length }}</span
            >
            <span
              v-else
              class="icon-JXC-shanchu iconfont"
              @click.stop="delClassFn(oneClass)"
            ></span>
          </div>
        </transition-group>
      </div>
    </div>
    <div class="classification-right">
      <div class="top-query">
        <div class="query-box">
          <el-input
            class="query-input"
            v-model.trim="queryCenter"
            placeholder="输入商品名称/查询码进行搜索"
          ></el-input>
          <el-button class="query-sousuo-btn" @click="queryCenter = ''"
            >重置</el-button
          >
        </div>

        <div class="title-tool-box">
          <el-button
            type="warning"
            @click="isShowStatistics = !isShowStatistics"
            >利润{{ isShowStatistics ? '隐藏' : '显示' }}</el-button
          >
          <el-button type="primary" @click="addCommodityFn">添加商品</el-button>
        </div>
      </div>
      <!-- 商品列表头部字段 -->
      <div class="right-title">
        <p
          class="t-item"
          v-for="item in commodityListInfo"
          :key="item.dataIndex"
          :style="{ flex: item.proportion, width: item.width }"
        >
          <span> {{ item.name }}</span>
          <span
            v-if="item.dataIndex === 'buyingPrice'"
            class="iconfont icon-JXC-mima"
            @click="isShowBuyingPrice = !isShowBuyingPrice"
          ></span>
        </p>
      </div>
      <div
        class="commodity-list-box"
        v-if="activeClass.commodityLists && activeClass.commodityLists.length"
      >
        <transition-group name="todo-group">
          <div
            class="commodity-list-item"
            :class="{ cartoon: isCartoon }"
            v-for="(oneDate, index) in activeClass.commodityLists"
            v-show="
              !queryCenter || queryCommodityIds.includes(oneDate.commodityId)
            "
            draggable="true"
            @dragstart="dragstart(index, 'commodity')"
            @dragenter="dragenter($event, index, 'commodity')"
            @dragover="dragover($event, index)"
            @dragend="dragend"
            :key="oneDate.commodityId"
            @click="toWeb()"
            @dblclick="editCommodityFn(oneDate)"
          >
            <!-- <div> -->
            <p class="statistics" v-if="isShowStatistics">
              <span>单利：</span>
              <span class="number">{{
                amend(oneDate.retailPrice, oneDate.buyingPrice, '-')
              }}</span>
              <span>总利：</span>
              <span class="number">{{
                amend(
                  amend(oneDate.retailPrice, oneDate.buyingPrice, '-'),
                  oneDate.inventoryNumber,
                  '*'
                )
              }}</span>
            </p>
            <div
              class="d-item"
              v-for="item in commodityListInfo"
              :key="item.dataIndex"
              :style="{ flex: item.proportion, width: item.width }"
            >
                <!-- 库存字段 -->
                <p v-if="item.dataIndex == 'inventoryNumber'">
                  <span class="iconfont icon-JXC-jinhuo" :class="{tips:oneDate['inventoryNumber'] <= oneDate['reminderCount']}"></span>
                  <span>{{
                  oneDate[item.dataIndex] === '' ? '-' : oneDate[item.dataIndex]
                }}</span>
                </p>
                <!-- 其他字段 -->
              <span
                v-else-if="item.dataIndex !== 'operation'"
                :class="{
                  hide: item.dataIndex == 'buyingPrice' && isShowBuyingPrice
                }"
              >
                {{
                  oneDate[item.dataIndex] === '' ? '-' : oneDate[item.dataIndex]
                }}
              </span>
              <!-- 操作字段 -->
              <p class="d-operate" v-else @click.stop>
                <!-- 删除 -->
                <span
                  class="operate-item del"
                  @click.stop="deleteCommodityFn(oneDate)"
                  >删除</span
                >
                <!-- 编辑 -->
                <span
                  class="operate-item edit"
                  @click.stop="editCommodityFn(oneDate)"
                  >编辑</span
                >
                <!-- 移动收藏夹 -->
                <span
                  class="operate-item move"
                  @click.stop="moveClassFn(oneDate)"
                  >移动</span
                >
              </p>
            </div>
            <!-- </div> -->
          </div>
        </transition-group>
      </div>
      <!-- 无数据展示 -->
      <div v-else class="list-box-no-data">
        <img class="no-data-img" src="@/assets/images/noData.png" />
        <p>暂无商品信息</p>
        <p class="add-commodity-btn" @click="addCommodityFn">添加商品</p>
      </div>
      <!-- 无查询商品提示 -->
      <div
        v-if="
          queryCenter &&
          queryCommodityIds.length == 0 &&
          activeClass.commodityLists.length
        "
        class="query-no-data"
      >
        <p>没有搜索的商品，可能在其他分类下</p>
        <p class="add-commodity-btn" @click="queryCenter = ''">重置</p>
      </div>
    </div>
    <!-- 新建商品 -->
    <addCommodity
      v-if="isAddCommodity"
      :editCommodity="editCommodity"
      @close="isAddCommodity = false"
      @confirmBox="confirmFn"
    ></addCommodity>
    <moveCommodity
      v-if="isMoveCommodity"
      :hideClass="activeClass.id"
      @close="isMoveCommodity = false"
      @confirmMove="confirmMoveFn"
    ></moveCommodity>
  </div>
</template>

<script>
import { reactive, toRefs, onBeforeMount, onMounted, watch } from 'vue';
import { setLS, getLS, toMoney, amend } from '@/utils/common.js';
import addCommodity from './addCommodity.vue';
import moveCommodity from './moveCommodity.vue';
import { commodityListInfo } from './commodity.js';
export default {
  name: '',
  components: {
    addCommodity,
    moveCommodity
  },
  setup() {
    const data = reactive({
      queryCenter: '', //检索内容
      queryCommodityIds: [], //查询出来的商品id
      isShowBuyingPrice: true,
      isShowStatistics: false,
      commodityListInfo,
      editCommodity: null, //编辑商品目标
      dragIndex: '', // 源对象的下标
      timeout: null,
      fileName: 'SubTop常用网站数据',
      isAddCommodity: false, //控制新建商品
      isMoveCommodity: false, //控制移动商品
      moveCommodityObject: null, //移动商品id
      idAddClass: false, //控制新建分类
      editClassName: '', //编辑分类名称
      commodityData: [], //商品数据
      initList: [
        //默认只有全部文件夹
        {
          className: '默认分类',
          id:`class_${Date.now().toString(16)}` , //唯一id
          commodityLists: []
        }
      ],
      activeClass: '', //选中分类
      editClass: '', //编辑进行时保存文件夹目标
      editClassName: '', //编辑进行时保存分类名称
      isCartoon: false //拖拽动画
    });
    onBeforeMount(() => {});
    onMounted(() => {
      data.commodityData = getLS('COMMODITY_DATA') || data.initList;
      data.activeClass = data.commodityData[0]; //初始化选中文件夹
    });
    watch(
      () => data.queryCenter,
      (val) => {
        queryCommodity();
      }
    );
    // 进行查询
    const queryCommodity = () => {
      data.queryCommodityIds = [];
      if (data.queryCenter) {
        data.activeClass.commodityLists.forEach((item) => {
          if (
            item.commodityName.includes(data.queryCenter) ||
            item.commodityQueryCode.includes(data.queryCenter)
          ) {
            data.queryCommodityIds.push(item.commodityId);
          }
        });
      }
    };
    // 拖拽相关开始
    // 源对象开始被拖动时触发
    const dragstart = (index, type) => {
      data.dragIndex = '';
      if (!index && type !== 'commodity') return; //默认分类不可拖拽，web可以
      if (type == 'commodity') {
        //web列表增加过渡
        data.isCartoon = true;
      }
      data.dragIndex = index;
    };
    // 源对象开始进入目标对象范围内触发
    const dragenter = (e, index, type) => {
      if (!index && type !== 'commodity') return; //默认分类不可拖拽 web可以
      e.preventDefault();
      if (!data.dragIndex && type !== 'commodity') return; // 文件夹不可拖拽到首个默认位置
      if (data.timeout !== null) {
        clearTimeout(data.timeout);
      }
      // 拖拽事件的防抖
      data.timeout = setTimeout(() => {
        // 判断需要操作的文件夹还是网站;
        const list =
          type == 'commodity'
            ? data.activeClass.commodityLists
            : data.commodityData;
        if (data.dragIndex !== index) {
          const source = list[data.dragIndex];
          list.splice(data.dragIndex, 1);
          list.splice(index, 0, source);
          // 排序变化后目标对象的索引变成源对象的索引
          data.dragIndex = index;
        }
      }, 100);
    };
    // 源对象在目标对象范围内移动时触发
    const dragover = (e) => {
      e.preventDefault();
    };
    // 拖拽结束
    const dragend = () => {
      data.isCartoon = false; //关闭web列表过渡
      setLS('COMMODITY_DATA', data.commodityData); //保存新的顺序
    };

    // 点击分类名称时，清除保存的编辑分类和名称
    const clickClass = (oneClass) => {
      data.editClass = '';
      data.editClassName = '';
      data.activeClass = oneClass;
      queryCommodity();
    };

    // 删除分类
    const delClassFn = (oneClass) => {
      // 点击删除选中当前分类
      clickClass(oneClass);
      ConfirmBox({
        title: '提示',
        content: `是否删除 ${data.activeClass.className} 分类 ?`
      })
        .then(() => {
          // 获取需要删除对象的下标
          const index = data.commodityData.findIndex(
            (item) => item.id === oneClass.id
          );
          if (index !== -1) {
            data.commodityData.splice(index, 1);
            setLS('COMMODITY_DATA', data.commodityData);
            Message({
              type: 'success',
              content: '删除成功'
            });
            // 删除后选中上一个分类
            data.activeClass = data.commodityData[index - 1];
          }
        })
        .catch(() => {
          // Message({
          //   type: 'warning',
          //   content: '取消'
          // });
        });
    };
    // 双击编辑分类名称
    const editClassNameFn = (oneClass) => {
      if (oneClass.className === '默认分类') return; //默认分类不可编辑
      data.editClass = oneClass;
      data.editClassName = oneClass.className;
    };
    // 确认时编辑分类名称
    const confirmEditClassNameFn = () => {
      if (data.editClassName.length > 10) {
        Message({
          type: 'error',
          content: '文件夹名称上限10个字符'
        });
        return;
      }
      // 有名称就进行修改
      if (data.editClassName) {
        data.editClass.className = data.editClassName;
        setLS('COMMODITY_DATA', data.commodityData);
        data.editClass = '';
        data.editClassName = '';
      }
    };
    // 新建分类
    const confirmAddClassFn = () => {
      if (data.editClassName.length > 10) {
        Message({
          type: 'error',
          content: '文件夹名称上限10个字符'
        });
        return;
      }
      if (data.editClassName) {
        const obj = {
          className: data.editClassName,
          id:`class_${Date.now().toString(16)}` , //唯一id
          commodityLists: []
        };
        data.commodityData.push(obj);
        setLS('COMMODITY_DATA', data.commodityData);
        data.idAddClass = false;
        data.editClassName = '';
        data.activeClass = obj; //创建后默认选中新建文件夹
      }
    };

    // 新增商品
    const addCommodityFn = () => {
      data.isAddCommodity = true;
      data.editCommodity = null;
    };
    // 确认新增商品 编辑
    const confirmFn = (commodity) => {
      // 这里判断是新增还是编辑
      const index = data.activeClass.commodityLists.findIndex(
        (i) => i.commodityId === commodity.commodityId
      );
      if (index == -1) {
        // 新增
        data.activeClass.commodityLists.push(commodity);
        Message({
          type: 'success',
          content: '添加成功'
        });
        data.queryCenter = ''; //检索内容
      } else {
        // 编辑
        data.activeClass.commodityLists[index] = commodity;
        Message({
          type: 'success',
          content: '编辑成功'
        });
      }
      setLS('COMMODITY_DATA', data.commodityData);
    };
    // 删除商品
    const deleteCommodityFn = (target) => {
      ConfirmBox({
        title: '提示',
        content: `是否删除 ${target.commodityName} 商品 ?`
      })
        .then(() => {
          // 找到删除的商品id
          const index = data.activeClass.commodityLists.findIndex(
            (i) => i.commodityId === target.commodityId
          );
          if (index !== -1) {
            // 删除后保存本地数据
            data.activeClass.commodityLists.splice(index, 1);
            setLS('COMMODITY_DATA', data.commodityData);
            Message({
              type: 'success',
              content: '删除成功'
            });
          }
        })
        .catch(() => {});
    };
    // 编辑商品
    const editCommodityFn = (target) => {
      data.isAddCommodity = true;
      data.editCommodity = target;
    };
    // 点击移动按钮
    const moveClassFn = (target) => {
      data.isMoveCommodity = true;
      data.moveCommodityObject = target;
    };
    // 确定移入
    const confirmMoveFn = (target) => {
      // 先将移动的商品从之前的分类中删除，再增加到移动的目标分类中去
      const index = data.activeClass.commodityLists.findIndex(
        (i) => i.commodityId === data.moveCommodityObject.commodityId
      );
      if (index !== -1) {
        // 删除后保存本地数据
        data.activeClass.commodityLists.splice(index, 1);
      }
      data.commodityData.forEach((item) => {
        if (item.id === target) {
          item.commodityLists.push(data.moveCommodityObject);
          setLS('COMMODITY_DATA', data.commodityData);
          Message({
            type: 'success',
            content: '移动成功'
          });
          data.isMoveCommodity = false;
        }
      });
    };
    return {
      moveClassFn,
      confirmMoveFn,
      queryCommodity,
      amend,
      editCommodityFn,
      deleteCommodityFn,
      confirmFn,
      addCommodityFn,
      clickClass,
      dragstart,
      dragend,
      dragover,
      dragenter,
      confirmEditClassNameFn,
      confirmAddClassFn,
      editClassNameFn,
      delClassFn,
      ...toRefs(data)
    };
  }
};
</script>
<style scoped lang="less">
.commodity-page {
  position: relative;
  height: 100%;
  width: 100%;
  padding-left: 200px;
  box-sizing: border-box;
  .add-favorites-zzc {
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 999;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.7);
    .add-favorites {
      width: 360px;
      left: 50%;
      top: 40%;
      transform: translate(-50%, -50%);
      background: #fff;
      border-radius: 4px;
      position: absolute;
      padding: 20px;
      z-index: 88;

      .add-item {
        .btn-box{
          margin-top:10px;
          float: right;
        }
      }
    }
  }

  .classification-left {
    position: absolute;
    padding-top: 40px;
    box-sizing: border-box;
    left: 0;
    width: 200px;
    height: 100%;
    .add-category {
      position: absolute;

      top: 5px;
      left: 10px;
    }

    .favorites-list {
      height: 100%;
      width: 100%;
      box-sizing: border-box;
      overflow: auto;
      border-right: 1px solid @HSE;
      .favorites-item {
        color: #000;
        line-height: 40px;
        overflow: hidden;
        padding: 0 20px;
        transition: 0.3s;
        cursor: pointer;

        .edit-input {
          float: left;
          width: 100px;
          height: 30px;
          padding: 0 10px;
          border: 1px solid @TSB;
          box-sizing: border-box;
          margin-top: 5px;
          outline: none;
          color: @TSA;
          &::-webkit-input-placeholder {
            color: #999;
            font-size: 12px;
          }
        }
        .oneClass-in-num {
          float: right;
          font-size: 12px;
        }
        .icon-JXC-shanchu {
          font-size: 14px;
          float: right;
          color: red;
          font-size: 12px;
          &:hover {
            color: red;
          }
        }
        .favorites-item-icon {
          float: left;
          margin-right: 10px;
          font-size: 18px;
          cursor: move;
        }
        .favorites-item-name {
          float: left;
          font-size: 14px;
        }
        &:hover {
          background: @TSD;
        }
        &.active {
          background: @TSA;
          color: #fff;
        }
      }
    }
  }
  .classification-right {
    width: 100%;
    height: 100%;
    min-width: 1000px;
    padding-top: 90px;
    box-sizing: border-box;
    position: relative;
    .top-query {
      position: absolute;
      width: 100%;
      height: 50px;
      top: 0px;
      left: 0;
      box-sizing: border-box;
      padding: 0 20px;
      padding-top: 10px;
      .query-box {
        width: 400px;
        .query-input {
          float: left;
          width: 300px;
        }
        .query-sousuo-btn {
          float: left;
          margin-left: 10px;
        }
      }

      .title-tool-box {
        float: right;
        .add-commodity-btn,
        .statistics-btn {
          float: left;
          font-size: 14px;
          color: #fff;
          padding: 0 10px;
          border-radius: 5px;
          margin-right: 10px;
          line-height: 30px;
          cursor: pointer;
          transition: 0.3s;
          color: @LS;
          background: @QLS;
          border: 1px solid @LLS;
          &:hover {
            opacity: 0.8;
          }
        }
        .statistics-btn {
          right: 100px;
          border: 1px solid @CS;
          background: @QCS;
          color: @CS;
        }
      }
    }
    .right-title {
      position: absolute;
      width: 100%;
      height: 40px;
      top: 50px;
      left: 0;
      background: @HSF;
      padding: 0 20px;
      box-sizing: border-box;
      font-size: 14px;
      display: flex;
      line-height: 40px;
      box-shadow: 0px 1px 0px #ccc;
      .icon-JXC-mima {
        cursor: pointer;
        margin-left: 5px;
        color: @HSC;
        transition: 0.3s;
        &:hover {
          color: @HSA;
        }
      }
    }
    .commodity-list-box {
      height: 100%;
      width: 100%;
      box-sizing: border-box;
      overflow-x: hidden;
      .commodity-list-item {
        position: relative;
        overflow: hidden;
        height: 42px;
        line-height: 42px;
        padding: 0 20px;
        cursor: pointer;
        font-size: 14px;
        display: flex;
        border-bottom: 1px solid @HSE;
        // transition: 0.3s;
        .statistics {
          position: absolute;
          right: 220px;
          border: 1px solid @CS;
          background: @QCS;
          height: 30px;
          margin-top: 5px;
          color: @CS;
          padding: 0 15px;
          border-radius: 4px;
          line-height: 30px;
          display: flex;
          .number {
            font-weight: 700;
            width: 70px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
        &.cartoon {
          transition: 0.3s;
        }
        .d-item {
          color: @HSB;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          .icon-JXC-jinhuo{
            color:@HSC;
            margin-right:10px;
            font-size:22px;
            &.tips{
              color:red;
         
            }
            &:hover{
              color:@RED;
            }
           
          }
          span {
            &.hide {
              opacity: 0;
            }
          }

          .d-operate {
            display: flex;
            .operate-item {
              flex: 1;
              height: 20px;
              line-height: 20px;
              text-align: center;
              opacity: 0.6;
              margin: 10px 5px;
              color: #fff;
              border-radius: 2px;
              &.del {
                background: @REA;
              }
              &.edit {
                background: @LS;
              }
              &.move {
                background: @TSA;
              }
              &:hover {
                opacity: 1;
              }
            }
          }
        }
        &:hover {
          background: @TSD;
        }
      }
    }
    .list-box-no-data,
    .query-no-data {
      color: @HSB;
      opacity: 0.8;
      .no-data-img {
        width: 400px;
        display: block;
        margin: 0px auto;
        margin-top: 100px;
        opacity: 0.6;
      }
      p {
        font-size: 14px;
        text-align: center;
      }
      .add-commodity-btn {
        color: #fff;
        cursor: pointer;
        margin-top: 10px;
        background: @TSA;
        width: 100px;
        line-height: 30px;
        margin: 10px auto;
        border-radius: 5px;
        transition: 0.3s;
        &:hover {
          background: @TSB;
        }
      }
    }
    .query-no-data {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>
